package com.spring.bucks.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spring.bucks.model.Coffee;
import com.spring.bucks.model.OrderCoffee;
import com.spring.bucks.model.Result;
import com.spring.bucks.service.CoffeeOrderService;
import com.spring.bucks.service.CoffeeService;
import com.spring.bucks.vo.CoffeeOrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 超
 * Create by fengc on  2022/8/20 12:56
 * coffee 业务类
 */
@Slf4j
@RestController
@RequestMapping("/coffeeOrder")
public class CoffeeOrderController {

    @Autowired
    private CoffeeService coffeeService;

    @Autowired
    private CoffeeOrderService orderService;

    /**
     * 通过集合ID批量查询数据库
     * @param ids
     * @return
     */
    @RequestMapping("/findCoffeesByIds")
    public Result findCoffeesByIds(@RequestParam(value = "name",required = false) String name, @RequestBody List<Integer> ids) {
        return Result.success(coffeeService.findByIds(name,ids));
    }

    @RequestMapping("/findCoffeeByName")
    public Result findCoffeeByName(@RequestParam("name") String name) {

        return Result.success(coffeeService.findByName(name));
    }

    /**
     * 翻页查询咖啡种类
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping("/findCoffeeList")
    public Result findCoffeeList(@RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                                       @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize) {
        log.info("findCoffeeList..pageNo={},pageSize={}.",pageNo,pageSize);
        return Result.success(coffeeService.findCoffeeList(pageNo,pageSize));
    }

    /**
     * 下单咖啡
     * @param requestMap
     * @return
     */
    @PostMapping("/buyCoffee")
    public Result buyCoffee(@RequestBody Map<String,Object> requestMap) {
        String customerName = (String)requestMap.get("customerName");
        List<Integer> coffeeIds = (List<Integer>) requestMap.get("coffeeIds");
        List<Coffee> coffees = Optional.ofNullable(coffeeService.listByIds(coffeeIds)).orElse(new ArrayList<>(2));
        if (coffees.size() <= 0) {
            return Result.fail("咖啡购买失败,点单的咖啡无货");
        }
        CoffeeOrderVO order = orderService.createOrder(customerName,coffees);
        return Result.success(order);
    }

    /**
     * 根据主键批量查询
     * @param orderIds
     * @return
     */
    @PostMapping("/findByOrderIds")
    public Result findByOrderIds(@RequestBody List<String> orderIds) {
        List<OrderCoffee> orderCoffees = orderService.listByIds(orderIds);
        return Result.success(orderCoffees);
    }

}
